package com.zetor.ms.facade.controller;

import com.zetor.ms.application.service.base.ITransactionService;
import com.zetor.ms.core.base.BaseController;
import com.zetor.ms.core.bo.Result;
import com.zetor.ms.core.util.LogUtils;
import io.seata.core.context.RootContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 事务 demo controller
 *
 * @author zlc
 * @date 6.30
 */
@RestController
public class TransactionController extends BaseController {
    @Autowired
    private ITransactionService demoService;

    /**
     * 分布式事务 seata
     * case1: client a -> client b， 成功commit
     * @return
     */
    @PostMapping("/v1/seata/clientb/case1")
    public Result seataCase1() {
        LogUtils.info("SestCase1--XID:" + RootContext.getXID());
        Long id = demoService.seataCase1();
        if (id != 0L) {
            return result("info.logic.success", id);
        }
        return result("error.logic.failed");
    }

    /**
     * 分布式事务 seata
     * case4: client a -> client b -> client c，client c发生exception
     * 全局事务rollback
     * @return
     */
    @PostMapping("/v1/seata/clientb/case2")
    public Result seataCase2() {
        LogUtils.info("SestCase2--XID:" + RootContext.getXID());
        Long id = demoService.seataCase4();
        if (id != 0L) {
            return result("info.logic.success", id);
        }
        return result("error.logic.failed");
    }

    /**
     * 分布式事务 seata
     * 模拟业务发药预结算
     * 全局事务rollback
     * @return
     */
    @PostMapping("/v1/seata/clientb/case3")
    public Result seataCase3() {
        LogUtils.info("SestCase3--XID:" + RootContext.getXID());
        Long id = demoService.seataCase9();
        if (id != 0L) {
            return result("info.logic.success", id);
        }
        return result("error.logic.failed");
    }

}
